import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterapptest1/HttpFactory.dart';
import 'package:flutterapptest1/JsonBean/news_dart_bean.dart';
import 'package:path_provider/path_provider.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:gbk2utf8/gbk2utf8.dart';

class NewsTestRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return NewsTestRouteState();
  }
}

Future<news_dart_bean> _newsData(int page) async {
  HttpFactory _httpFactory = HttpFactory();
  var respones = await _httpFactory.getData(url: '/getWangYiNews', page: page);
  Map<String, dynamic> map = json.decode(respones.toString());
  var news = news_dart_bean.fromJson(map);
  return news;
}

class NewsTestRouteState extends State<NewsTestRoute> {
  Widget _widget;
  static const loadingTag = "##loading##"; //表尾标记
  var _words = <String>[loadingTag];
  var _page = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _widget = Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            child: LinearProgressIndicator(),
            height: 8.0,
            width: 200,
          ),
          Text('加载中...')
        ],
      ),
    );
    _newsData(_page).then((onValue) {
      setState(() {
        if (onValue.code != 200) {
          _widget = Center(
            child: Text('加载失败'),
          );
        } else {
          _widget = CustomScrollView(
            slivers: <Widget>[
              SliverAppBar(
                backgroundColor: Colors.transparent,
                title: Text('网易新闻'),
                pinned: false,
                floating: true,
                expandedHeight: 250,
                flexibleSpace: Padding(
                  padding: EdgeInsets.all(0),
                  child: PageView.builder(
                    itemBuilder: (context, index) {
                      return Stack(
                        children: <Widget>[
                          Container(
                            child: Image.network(
                              onValue.result[index].image,
                              fit: BoxFit.cover,
                            ),
                            constraints: BoxConstraints(
                                minWidth: double.infinity,
                                minHeight: double.infinity),
                          ),
                          Positioned(
                            bottom: 0,
                            left: 20,
                            child: Container(
                              child: SizedBox(
                                child: Text(
                                  onValue.result[index].title,
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 15),
                                ),
                                width: 300,
                              ),
                            ),
                          )
                        ],
                      );
                    },
                    itemCount: 4,
                  ),
                ),
              ),
              SliverPadding(
                padding: EdgeInsets.all(5),
              ),
              SliverList(
                delegate: SliverChildBuilderDelegate((context, index) {
                  var data = onValue.result[index + 4];
                  return Column(
                    children: <Widget>[
                      ListTile(
                          title: Text(data.title),
                          subtitle: Text(data.passtime),
                          leading: Image.network(data.image),
                          dense: true,
                          onTap: () {
                            Navigator.push(context,
                                MaterialPageRoute(builder: (context) {
                              return CustomWebView(
                                  data.title, data.path, _page);
                            }));
                          }),
                      Divider(
                        height: 1,
                      )
                    ],
                  );
                }, childCount: onValue.result.length - 4),
              )
            ],
          );
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Center(
        child: _widget,
      ),
    );
  }
}

class CustomWebView extends StatefulWidget {
  CustomWebView(this.title, this.url, this.naxtPage);

  final String url;
  final String title;
  final int naxtPage;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    print(url);
    return CustomWebViewState();
  }
}

class CustomWebViewState extends State<CustomWebView> {
  var _dataMap = HashMap();

  Future _hasData() async {
    var content = await HttpFactory().getHtmlUrl(url: widget.url);
    var news = await _newsData(widget.naxtPage);
    _dataMap['content'] = content;
    _dataMap['news'] = news;
    return _dataMap;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder(
        future: _hasData(),
        builder: (context, sn) {
          if (sn.connectionState == ConnectionState.done) {
            news_dart_bean news = sn.data['news'];
            String content = sn.data['content'];
            return Scrollbar(
              child: ListView.separated(
                  itemBuilder: (context, index) {
                    Widget widget;
                    if (index == 0) {
                      widget = SingleChildScrollView(
                        child: Center(
                          child: Column(
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.symmetric(
                                    vertical: 5, horizontal: 20),
                                child: Text(
                                  RegexMatch(sn.data['content']).getNewsTitle(),
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 25),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.symmetric(
                                    vertical: 5, horizontal: 20),
                                child: Row(
                                  children: <Widget>[
                                    Text(
                                      RegexMatch(sn.data['content'])
                                          .getNewsTime(),
                                      style: TextStyle(color: Colors.grey),
                                    ),
                                    SizedBox(
                                      width: 40,
                                    ),
                                    Text(
                                      '来源：${RegexMatch(sn.data['content']).getNewsSource()}',
                                      style: TextStyle(color: Colors.grey),
                                    )
                                  ],
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.symmetric(
                                    vertical: 5, horizontal: 10),
                                child: Divider(),
                              ),
                              Padding(
                                padding: EdgeInsets.symmetric(
                                    vertical: 10, horizontal: 20),
                                child: Text(RegexMatch(sn.data['content'])
                                    .getNewsContent()),
                              ),
                              SizedBox(
                                height: 20,
                                child: Container(
                                  color: Color(0x09000000),
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    } else {
                      widget = ListTile(
                        title: Text(news.result[index - 1].title),
                        leading: Image.network(news.result[index - 1].image),
                        dense: true,
                        onTap: () {
                          Navigator.pushReplacement(context,
                              MaterialPageRoute(builder: (context) {
                            return CustomWebView(
                                news.result[index - 1].title,
                                news.result[index - 1].path,
                                this.widget.naxtPage + 1);
                          }));
                        },
                      );
                    }
                    return widget;
                  },
                  separatorBuilder: (context, index) {
                    return Divider(
                      height: 10,
                    );
                  },
                  itemCount: news.result.length + 1),
            );
          } else {
            return Center(
              child: LinearProgressIndicator(),
            );
          }
          return null;
        },
      ),
    );
  }
}

class RegexMatch {
  final String content;

  RegexMatch(this.content);

  String getNewsTitle() {
    String regex = 'post_content_main([\\s\\S]*?)h1>([\\s\\S]*?)(?=</h1>)';
    RegExp regExp = RegExp(regex, multiLine: true);
    var allMatch = regExp.firstMatch(content);
    return allMatch.group(2);
  }

  String getNewsTime() {
    RegExp regExp = RegExp(r'post_time_source([\s\S]*?)(?=ne_article_source)');
    var match = regExp.firstMatch(content);
    RegExp regExpTime = RegExp(r'\d.*\d');
    return regExpTime.firstMatch(match.group(1)).group(0);
  }

  String getNewsSource() {
    RegExp regExp = RegExp(
        r'post_time_source([\s\S]*?)(?=ne_article_source)([\s\S]*?)>(.*?)</a>');
    var match = regExp.firstMatch(content);
    return match.group(3);
  }

  String getNewsContent() {
    RegExp regExp = RegExp(r'class="otitle"([\s\S]*?)ep-source cDGray');
    var match0 = regExp.firstMatch(content);
    RegExp regExpContext = RegExp('(?<=<p>)(.*?)(?=</p>)');
    var match1 = regExpContext.allMatches(match0.group(0));
    String newsContect;
    for (Match match in match1) {
      String s = match
          .group(0)
          .replaceAll("\<!--StartFragment-->", "")
          .replaceAll("\<!--EndFragment-->", "");
      if (s.contains("<") && s.contains(">")) {
        RegExp regExp = RegExp(r'<[\s\S]*?>');
        var s0 = regExp.allMatches(s);
        for (Match match in s0) {
          s = s.replaceAll(match.group(0), "");
        }
      }
      if (s.trim() == '') {
        continue;
      }
      if (newsContect != null) {
        newsContect += "\n       " + s;
      } else {
        newsContect = "      " + s;
      }
    }
    return newsContect;
  }
}
